package com.lg.startertemplate.controller;

import cn.hutool.core.util.StrUtil;
import com.lg.startertemplate.dao.DaoCenter;
import com.lg.startertemplate.dao.impl.UserDao;
import com.lg.startertemplate.domain.TUser;
import com.lg.startertemplate.povo.PageResult;
import com.lg.startertemplate.povo.UserRes;
import com.lg.startertemplate.povo.UserResp;
import com.lg.startertemplate.utiles.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "数据操作")
@Slf4j
public class UserController {

    @Autowired
    private UserDao userDao;





    @GetMapping("findAllById")
    public TUser findAllById(Long id) {
        TUser allById = userDao.findAllById(id);
        return allById;
    }


    //============================修改============================
    @GetMapping("updateSomeThing")
    public Integer updateSomeThing() {
        Integer updateName = userDao.updateSomeThing("updateName", 7);
        return updateName;
    }

    //============================@Query============================
    @GetMapping("querySomeByMyself")
    public List<TUser> querySomeByMyself() {
        List tUsers = userDao.querySomeByMyself(2, 1);
        return tUsers;
    }

    @GetMapping("querySome")
    public List<TUser> querySome() {
        Pageable pageable = PageRequest.of(1, 2,
                new Sort(Sort.Direction.ASC,
                        "name"));
        List<TUser> b = userDao.querySome("b", pageable);
        return b;
    }


    @GetMapping("querySome2")
    public PageResult querySome2() {
        Pageable pageable = PageRequest.of(1, 2,
                new Sort(Sort.Direction.ASC,
                        "name"));
        Page<TUser> b = userDao.querySome2("b", pageable);
        PageResult pageResult = PageResult.formatByPageDate(b);
        return pageResult;
    }

    @GetMapping("querySome3")
    public PageResult querySome3() {
        Pageable pageable = PageRequest.of(1, 2,
                new Sort(Sort.Direction.ASC,
                        "name"));

        Page<TUser> b = userDao.querySome3("b", pageable);
        PageResult pageResult = PageResult.formatByPageDate(b);
        return pageResult;
    }

    @GetMapping("querySome4")
    public PageResult querySome4() {
        Pageable pageable = PageRequest.of(1, 2,
                new Sort(Sort.Direction.ASC,
                        "name"));

        Page<TUser> b = userDao.querySome4("b", pageable);
        PageResult pageResult = PageResult.formatByPageDate(b);
        return pageResult;
    }


    //============================时间============================

    /**
     * 查看创建时间和修改时间 是否生成
     */
    @GetMapping("createRandUser")
    public ResponseEntity<TUser> createRandUser() {
        TUser tUser = new TUser();
        tUser.setAge(new Random().nextInt(10) + 1);
        tUser.setWZ("address");
        tUser.setGridSet("4327");
        tUser.setName("aa");
        userDao.save(tUser);
        return new ResponseEntity(tUser, HttpStatus.OK);
    }

    /**
     * 查看创建时间和修改时间的变换
     *
     * @param userid
     * @return
     */
    @PutMapping("editRandUser")
    public ResponseEntity<TUser> editRandUser(Long userid) {
        Optional<TUser> userP = userDao.findById(userid);
        TUser tUser = userP.get();
        tUser.setAge(new Random().nextInt(10) + 1);
        userDao.save(tUser);
        return ResponseEntity.ok(tUser);
    }

    /**
     * 创建时间和修改时间 都可自己修改
     * 2020-07-30 19:29:17.61
     * 2020-07-30 19:29:17
     * <p>
     * getOne会出现序列化问题  尽量用findById !!! 必然有它的到里
     */
    @PutMapping("editUserCreateTime")
    public ResponseEntity<TUser> editUserCreateTime(Long userid, String time) {
        TUser user = userDao.findById(userid).get();
        user.setCreateTime(new Date(TimeUtils.strFormatLong(time)));
        userDao.save(user);
        return ResponseEntity.ok(user);
    }


    //============================自定义返回============================

    /**
     * 三种方法 无谁优谁劣
     * 情况不用 用的不同
     */
    @GetMapping("resultByMyself3")
    public List<TUser> resultByMyself3() {
        List<Map<String, Object>> maps = userDao.queryBySome();
        List<TUser> tusers = TUser.getTusers(maps);
        return tusers;
    }

    @GetMapping("resultByMyself2")
    public List<UserRes> resultByMyself2() {
        List<UserRes> users = userDao.findByNameEndingWith("b");
        log.debug("getAge: " + users.get(0).getAge().toString());
        return users;
    }

    @GetMapping("resultByMyself1")
    public List<UserResp> resultByMyself1() {
        List<UserResp> users = userDao.findByNameStartingWith("b");
        log.debug("getAge: " + users.get(0).getAge().toString());
        return users;
    }

    //jap 查询
    @GetMapping("japSumAgeByName")
    public  List<TUser>  japSumAgeByName() {
        List<TUser> tUsers = userDao.sumAgeByName();
        return tUsers;
    }
    //jap 查询
    @GetMapping("japDistinctName")
    public  Set<String> japDistinctName() {
        Set<String> res = userDao.distinctName();
        return res;
    }
    //jap 查询
    @GetMapping("jpaQueryInSome")
    public  List<TUser> jpaQueryInSome() {
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(1l);
        ids.add(3l);
        ids.add(5l);
        ids.add(7l);
        List<TUser> tUsers = userDao.queryInSome( ids);
        return tUsers;
    }



    //============================模糊查询============================
    @GetMapping("testLike")
    public List<TUser> testLike() {

        return userDao.findTop2ByNameLike("b%a%d");
//        return userDao.findByNameLike("b%a%d");
//        return userDao.findByNameStartingWith("b");
//        return userDao.findByNameEndingWith("b");
//        return userDao.findByNameContaining("b");
    }

    //============================大于小于等于============================
    @GetMapping("findByAgeLessThan")
    public List<TUser> testLessGreater() {
//        return userDao.findByAgeLessThan(2);
        return userDao.findByAgeGreaterThanEqual(2);
    }


    @GetMapping("testBetween")
    public List<TUser> testBetween() {
//        return userDao.findByNameBetween("a", "c");
        return userDao.findByAgeBetween(1, 3);
    }

    //============================分页查找============================

    /**
     * @param queryKey 搜索关键字为空  则搜索全部
     * @RequestParam required 默认为 true 必须输入
     */
    @GetMapping("queryByName")
    public PageResult queryByName(
            @ApiParam(value = "当前页,从1开始") @RequestParam(defaultValue = "1") Integer currentPage,
            @ApiParam(value = "每页条目数") @RequestParam(defaultValue = "50") Integer pageSize,
            @ApiParam(value = "搜索关键字") @RequestParam(required = false) String queryKey,
            @ApiParam(value = "排序列名", allowableValues = "createTime") @RequestParam(required = false, defaultValue = "createTime") String orderColumn,
            @ApiParam(value = "排序类型", allowableValues = "desc, asc") @RequestParam(required = false, defaultValue = "desc") String orderType) {

        Pageable pageable = PageRequest.of(currentPage - 1, pageSize,
                new Sort((orderType != null && orderType.equals("asc")) ? Sort.Direction.ASC : Sort.Direction.DESC,
                        orderColumn));
        Page<TUser> users = null;

        if (StrUtil.isEmpty(queryKey)) {
//            搜全部 分页 并排序
            users = userDao.findAll(pageable);

        } else {
//            指定搜索关键位置 分页 并排序
            users = userDao.findByNameLikeOrGridSetLikeOrderByIdDescNameAsc(queryKey, queryKey, pageable);
        }

        return PageResult.formatByPageDate(users);
    }


}
